package com.itjiange.reglg.interceptor;

import com.itjiange.reglg.common.RedisCode;
import com.itjiange.reglg.utils.NetUtils;
import com.itjiange.reglg.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 接口防刷
 *
 * @author ItJiange
 * @date 2023/11/17
 */
@Slf4j
@Component
public class IPInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtils redisUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取 ip 地址
        String ipAddress = NetUtils.getIpAddress(request);
        // 获取请求路径
        String context = request.getRequestURI().substring(1);
        // 组合生成 key
        String redisKey = RedisCode.FLUSH_PORT.join(ipAddress, context);
        // 接口防刷
        return redisUtils.isAllowFlush(redisKey);
    }
}
